package zss.ocr;

import java.util.HashMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.Object;
import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.speech.AipSpeech;

public class baidu_ocr_demo {
	// 设置APPID/AK/SK
	public static final String APP_ID = "10184043";
	public static final String API_KEY = "l0KhGcNldf7RXMb5km9YQscB";
	public static final String SECRET_KEY = "oKmbjnfiGhnsfUGXCNglYSxirYVeELIP";

	public static void main(String[] args) {
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);

		// 可选：设置代理服务器地址, http和socket二选一，或者均不设置
		// client.setHttpProxy("proxy_host", proxy_port); // 设置http代理
		// client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理

		// 调用接口
		String path = "/Users/zss/Desktop/2/QQ20170925-141232@2x.png";
//		JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
//		System.out.println(res.toString(2));
		receiptRecognition(client);

	}

	public static void receiptRecognition(AipOcr client) {
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("probability", "true");

		// 参数为本地图片路径
		String imagePath = "/Users/zss/Desktop/2/QQ20170925-141232@2x.png";
		JSONObject response = client.receipt(imagePath, options);
		System.out.println(response.toString());
		byte [] s = new byte[4];
		
		// 参数为本地图片文件二进制数组
//		byte[] file = readImageFile(imagePath);
//		JSONObject response1 = client.receipt(file, options);
//		System.out.println(response1.toString());
	}

	public byte[] readImageFile(String path) {

		FileInputStream fileInput = null;
		try {
			File file = new File(path);
			if (!file.exists()) {
				file.createNewFile();
			}
			byte[] buffer = new byte[1024];
			fileInput = new FileInputStream(file);
			int byteread = 0;
			// byteread表示一次读取到buffers中的数量。
			while ((byteread = fileInput.read(buffer)) != -1) {
				System.out.write(buffer, 0, byteread);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				if (fileInput != null) {
					fileInput.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}
}
